package com.zzq.config.wx;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

@Component
public class SignV3Utils {
    @Autowired
    WxPayConfigLoader configLoader;


    @Autowired
    private WxJsapiConfig wxJsapiConfig;
    /**
     * 作用：使用字段appId、timeStamp、nonceStr、package计算得出的签名值
     * 场景：根据微信统一下单接口返回的 prepay_id 生成调启支付所需的签名值
     * @param appId
     * @param timestamp
     * @param nonceStr
     * @param pack package
     * @return
     * @throws Exception
     */
    public String getSign(String appId, long timestamp, String nonceStr, String pack) throws Exception{
        String message = buildMessage(appId, timestamp, nonceStr, pack);
        String paySign= sign(message.getBytes("utf-8"));
        return paySign;
    }

    private String buildMessage(String appId, long timestamp, String nonceStr, String pack) {
        return appId + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + pack + "\n";
    }
    private String sign(byte[] message) throws Exception{
        Signature sign = Signature.getInstance("SHA256withRSA");
        //这里需要一个PrivateKey类型的参数，就是商户的私钥。
        //获取商户私钥
        PrivateKey privateKey =  loadPrivateKeyFromPEM(wxJsapiConfig.getPrivatekey());
        sign.initSign(privateKey);
        sign.update(message);
        return Base64.getEncoder().encodeToString(sign.sign());
    }
    public static PrivateKey loadPrivateKeyFromPEM(String pemFilePath) throws Exception {
        BufferedReader reader = new BufferedReader(new FileReader(pemFilePath));
        StringBuilder privateKeyPEM = new StringBuilder();
        String line;

        // 从PEM文件中读取私钥数据
        while ((line = reader.readLine()) != null) {
            if (line.contains("-----BEGIN PRIVATE KEY-----") || line.contains("-----END PRIVATE KEY-----")) {
                continue;
            }
            privateKeyPEM.append(line);
        }
        reader.close();

        // 解码Base64编码的私钥数据
        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyPEM.toString());

        // 创建PKCS8EncodedKeySpec对象并生成PrivateKey对象
        KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // 根据私钥类型选择适当的算法
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        return privateKey;
    }
}

